# Copyright (C) 2009, 2010 Nathan Grubb

import Cookie as CookieModule # Avoid interfering with the Cookie class below
import os

def get_cookie(name):
    """Retrieve a cookie by name. Returns a new Cookie instance (though don't
       depend on the value being set - if it can't find your cookie, it will 
       return Cookie(name) (It will return None when 1.2 is released.) This
       will not give you an expiration back, though usually only the
       browser will need to manage expirations.
    """
    if "HTTP_COOKIE" in os.environ:
        cookies = os.environ["HTTP_COOKIE"]
        cookies = cookies.split("; ")
        handler = {}

        for cookie in cookies:
            cookie = cookie.split("=")
            handler[cookie[0]] = cookie[1]

        if name in handler:
            return Cookie(name, handler[name])
    return Cookie(name)

class Cookie(object):
    """An even more abstracted version of the standard library's Cookie.SimpleCookie.
    """
    def __init__(self, name, value=None, expiration=None):
        """Expiration is in seconds."""
        self.name = str(name)
        self.expiration = expiration
        self.value = value
        self.cookie = CookieModule.SimpleCookie()
        self.cookie[self.name] = self.value

        if type(self.expiration) == int:
            self.cookie[self.name]["expires"] = self.expiration

    def __str__(self):
        """Print a Cookie() to get a representation that can be sent to a browser."""
        return str(self.cookie)

    def get(self):
        """This is provided for backwards compatibility (until 1.2) and will 
           return get_cookie(self.name). As mentioned, use get_cookie instead.
        """
        return get_cookie(self.name)

    def print_header(self):
        """This is provided for backwards compatibility and will be removed in 
           Toasted 1.2. You can get the same result printing a Cookie() object,
           or even better, using toased.template.render_to_response or 
           toasted.http.HttpResponse() to manage your headers.
        """
        print self
        
    def set_expiration(self, expiration):
        """This is provided for backwards compatibility and will be removed in 
           Toasted 1.2
        """
        self.expiration = expiration
    
    def set_value(self, value):
        """This is provided for backwards compatibility and will be removed in 
           Toasted 1.2
        """
        self.value = value